package com.ewing.extranal.im;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ewing.extranal.im.contant.ImEvent;
import com.google.gson.Gson;

/**
 * 类/接口注释
 * 
 * @author tansonlam
 * @createDate 2016年4月21日
 * 
 */
@ServerEndpoint(value = "/im/chat", configurator = GetHttpSessionConfigurator.class)
public class ImMessageWebSocket {

    private static Logger logger = Logger.getLogger(ImMessageWebSocket.class);

    private Long imUserId;
    protected Session session;;
    private HttpSession httpSession;
    protected final static Gson gson = new Gson();
    private ImMessageController imMessageController;

    public ImMessageWebSocket() {
    }

    @OnOpen
    public void start(Session session, EndpointConfig config) {
        this.session = session;
        this.httpSession = (HttpSession) config.getUserProperties()
                .get(HttpSession.class.getName());
        this.imUserId = (Long) httpSession.getAttribute("imUserId");
        logger.info("start connection imUserId:" + imUserId);
        ImConnectionPool.add2Pool(imUserId, this);
        imMessageController = new ImMessageController(imUserId);
        imMessageController.getContactList();
    }

    public Session getSession() {
        return session;
    }

    @OnClose
    public void end() {
        logger.info("end connection imUserId:" + imUserId);
        ImConnectionPool.remove(imUserId);
    }

    @OnMessage
    public void incoming(String recMessage, EndpointConfig config) {
        try {
            String[] recMessageArr = StringUtils.split(recMessage, "|@|");
            if (recMessageArr.length == 0)
                return;
            String event = recMessageArr[0];
            if (ImEvent.REQ_SENDMSG.getValue().equals(event)) {
                Long sendUserId = Long.valueOf(recMessageArr[1]);
                String sendMessage = recMessageArr[2];
                imMessageController.recordMessage(sendUserId, sendMessage);
            } else if (ImEvent.REQ_CHATHIS.getValue().equals(event)) {
                Long relUserId = Long.valueOf(recMessageArr[1]);
                String lastMessageId = recMessageArr[2];
                imMessageController.getChatHistory(relUserId, lastMessageId);
            } else if (ImEvent.REQ_NEWCHAT.getValue().equals(event)) {
                Long relUserId = Long.valueOf(recMessageArr[1]);
                imMessageController.newChat(relUserId);
            } else if (ImEvent.REQ_UPDATEREAD.getValue().equals(event)) {
                Long relUserId = Long.valueOf(recMessageArr[1]);
                String messageIds = recMessageArr[2];
                imMessageController.update2Read(relUserId, StringUtils.split(messageIds, ","));
            } else if (ImEvent.REQ_CONTACT.getValue().equals(event)) {
                imMessageController.getContactList();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        // logger.error("Chat Error: " + t.toString(), t);
        logger.info("met error in connection imUserId:" + imUserId);
       // ImConnectionPool.remove(imUserId);
    }

}
